# coding=utf-8
import json
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from backstage.sutra.utils import viewutils
from backstage.sutra import forms


class CategoryList(APIView):
    '''
    经书类列表
    '''

    def get(self, request):
        form = forms.Sutras(request.query_params)
        getall = request.query_params.get('getall', 0)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })
        rdata = form.cleaned_data
        data = viewutils.sutra_category_list(
            rdata['offset'], rdata['limit'], getall=getall)
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data})


class Category(APIView):
    '''
    category operation
    '''

    def post(self, request):
        name = request.data.get('name')
        desc = request.data.get('desc')
        cover_img = request.FILES.get('cover_img')
        if not cover_img:
            return Response({'status': 400})
        img_url = viewutils.handel_sutra_img(cover_img)
        viewutils.create_sutra_category(name, desc, img_url)
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': {'cover_img_url': img_url}})

    def get(self, request, sutra_id=None):
        if not sutra_id:
            return Response({'status': 400})
        res = viewutils.get_sutra_category(sutra_id)
        if res is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': res})

    def put(self, request, sutra_id=None):
        if not sutra_id:
            return Response({'status': 400})
        cover_img = request.FILES.get('cover_img')
        data = {
            'name': request.data.get('name'),
            'description': request.data.get('desc')}
        if cover_img:
            img_url = viewutils.handel_sutra_img(cover_img)
            data['cover_url'] = img_url
        res = viewutils.update_sutra_category(sutra_id, data)
        if res is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees'})

    def delete(self, request, sutra_id=None):
        if not sutra_id:
            return Response({'status': 400})
        viewutils.del_sutra_category(sutra_id)
        return Response({
            'status': 200,
            'msg': 'succees'})


class EditionList(APIView):
    '''
    edition list
    '''

    def get(self, request, sutra_id=None):
        form = forms.SutraEdition(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })
        rdata = form.cleaned_data
        data = viewutils.sutra_edition_list(
            sutra_id, rdata['offset'], rdata['limit'])
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data})


class EditionDetails(APIView):
    '''
    edition details
    '''

    def get(self, request, edition_id=None):
        if not edition_id:
            return Response({'status': 400})
        if int(edition_id) < 0:
            return Response({'status': 400})
        data = viewutils.get_edition_details(edition_id)
        if data is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data})


class Edition(APIView):
    '''
    edition operation
    '''

    def get(self, request, edition_id=None):
        if not edition_id:
            return Response({'status': 400})
        if int(edition_id) < 0:
            return Response({'status': 400})
        need_num = request.query_params.get('need_num', 8)
        data = viewutils.no_import_page(edition_id, int(need_num))
        if data is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees', 'data': data})

    def post(self, request):
        sutra_id = request.data.get('sutra_id')
        cover_img = request.FILES.get('cover_img')
        char_txt = request.FILES.get('char_txt')
        if not sutra_id or not cover_img or not char_txt:
            return Response({'status': 400})
        sutra = viewutils.get_sutra(sutra_id)
        if sutra is False:
            return Response({'status': 404})
        create_data = {
            'art_no': request.data.get('art_no', 'no'),
            'sutra_id': sutra_id,
            'name': request.data.get('name'),
            'description': request.data.get('desc', 'no'),
            'author': request.data.get('author', 'no'),
            'total_page_num': request.data.get('total_page_num', 0),
            'total_char_num': request.data.get('total_char_num', 0),
            'price': request.data.get('price', 0),
            'print_price': request.data.get('price', 0),
            'cover_url': 'no',
        }
        edition = viewutils.create_sutra_edition(create_data)
        img_url = viewutils.handel_edition_img(cover_img, edition.id)
        char_num, char_url = viewutils.handel_edition_char(
            char_txt, edition.id)
        viewutils.update_sutra_edition(edition, {
            'cover_url': img_url, 'total_char_num': char_num,
            'char_url': char_url})
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': {'id': edition.id}})

    def put(self, request, edition_id=None):
        if not edition_id:
            return Response({'status': 400})
        edition = viewutils.get_edition(edition_id)
        if edition is False:
            return Response({'status': 404})

        update_data = {
            'sutra_id': request.data.get('sutra_id'),
            'name': request.data.get('name'),
            'total_page_num': request.data.get('total_page_num'),
            'price': request.data.get('price'),
            'description': request.data.get('desc'),
            'cover_url': None,
            'char_url': None,
        }
        cover_img = request.data.get('cover_img')
        char_txt = request.data.get('char_txt')
        if cover_img:
            img_url = viewutils.handel_edition_img(cover_img, edition_id)
            update_data['cover_url'] = img_url
        if char_txt:
            char_num, char_url = viewutils.handel_edition_char(
                char_txt, edition_id)
            update_data['char_url'] = char_url
            update_data['total_char_num'] = char_num
        viewutils.update_sutra_edition(edition, update_data)
        return Response({'status': 200, 'msg': 'succees'})

    def delete(self, request, edition_id=None):
        if not edition_id:
            return Response({'status': 400})
        viewutils.del_sutra_edition(edition_id)
        return Response({'status': 200, 'msg': 'succees'})


class EditionPageList(APIView):
    '''
    edition page list
    '''

    def get(self, request, edition_id=None):
        if not edition_id:
            return Response({'status': 400})
        form = forms.SutraEditionPageList(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })
        rdata = form.cleaned_data
        data = viewutils.edition_page_list(
            edition_id, rdata['offset'], rdata['limit'])
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data})


class EditionPage(APIView):
    '''
    page operation
    '''

    def get(self, request):
        edition_id = request.query_params.get('edition_id')
        page_num = request.query_params.get('page_num')
        page_id = request.query_params.get('page_id')
        if page_num:
            data = viewutils.get_edition_page_by_pagenum(
                edition_id, page_num, return_obj=False)
        elif page_id:
            data = viewutils.get_edition_page(page_id, return_obj=False)
        else:
            return Response({'status': 404})
        if data is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'success',
            'data': data})

    def post(self, request):
        edition_id = request.data.get('edition_id')
        content_img = request.FILES.get('content_img')
        page_num = request.data.get('page_num')
        if not edition_id or not content_img or not page_num:
            return Response({'status': 400})
        if viewutils.get_edition_page_by_pagenum(
                edition_id, page_num, return_obj=False):
            return Response({'status': 409})
        img_data = viewutils.handle_page_img(
            edition_id, content_img, page_num)
        try:
            viewutils.create_edition_page(edition_id, {
                'sutra_edition_id': edition_id,
                'content': 'no', 'sf': img_data['sf'],
                'original_cimg_url': img_data['original_cimg_url'],
                'hyaline_cimg_url': img_data['hyaline_cimg_url'],
                'twov_cimg_url': img_data['twov_cimg_url'],
                'page_num': page_num, 'total_char_num': 0})
        except Exception as e:
            return Response({'status': 409})
        img_url = '{0}{1}'.format(
            settings.SELF_DOMAIN, img_data['original_cimg_url'])
        return Response({
            'status': 200, 'msg': 'succees',
            'data': {
                'img_url': img_url}})

    def put(self, request, page_id=None):
        if not page_id:
            return Response({'status': 400})
        page = viewutils.get_edition_page(page_id)
        if page is None:
            return Response({'status': 404})
        if page['status'] == 1:
            return Response({'status': 409})
        update_data = {
        }
        content_img = request.FILES.get('content_img')
        if content_img:
            img_data = viewutils.handle_page_img(
                page.sutra_edition_id,
                content_img, page.page_num)
            update_data['original_cimg_url'] = img_data['original_cimg_url']
            update_data['hyaline_cimg_url'] = img_data['hyaline_cimg_url']
            update_data['twov_cimg_url'] = img_data['twov_cimg_url']
            update_data['sf'] = img_data['sf']
        try:
            viewutils.update_edition_page(page, update_data)
            return Response({'status': 200, 'msg': 'succees'})
        except Exception as e:
            return Response({'status': 409})

    def delete(self, request, page_id=None):
        if not page_id:
            return Response({'status': 400})
        res = viewutils.del_edition_page(page_id)
        if res is None:
            return Response({'status': 404})
        if res is False:
            return Response({'status': 409})
        return Response({'status': 200, 'msg': 'succees'})


class EditionPageScan(APIView):
    '''
    edition page scan
    '''

    def post(self, request, page_id=None):
        if not page_id:
            return Response({'status': 400})
        data = viewutils.edition_page_scan(page_id)
        if data is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data})


class EditionPageWordsPositon(APIView):
    '''
    words position
    '''

    def get(self, request, page_id=None):
        if not page_id:
            return Response({'status': 400})
        edition_id = request.query_params.get('edition_id', None)
        data = viewutils.get_img_words(page_id, edition_id)
        if data is False:
            return Response({'status': 404})
        return Response({
            'status': 200,
            'msg': 'succees',
            'data': data
        })

    def post(self, request, page_id=None):
        edition_id = request.data.get('edition_id')
        word_imgurl = json.loads(
            request.data.get('word_imgurl'))
        words = json.loads(request.data.get('words'))
        page_id = request.data.get('page_id')
        res = viewutils.page_word_location(
            page_id, edition_id, word_imgurl, words)
        if res is False:
            return Response({'status': 404})
        return Response({'status': 200, 'msg': 'succees'})


class UploadImg(APIView):
    def post(self, request):
        base64img = request.data.get('base64img', None)
        page_id = request.data.get('page_id', None)
        edition_id = request.data.get('edition_id', None)
        word_url = viewutils.save_hyaline_img(
            viewutils.base64_to_img(base64img),
            page_id, edition_id)
        return Response({
            'status': 200,
            'data': {'word_url': word_url}})
